package com.sky.loveshop.manager;

import com.sky.loveshop.entity.MqttMessage;
import com.sky.loveshop.service.MqttMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author xcy
 * @version V1.0
 * @description
 * @date 2024/9/6 21:31
 */
@Slf4j
@Component("default")
public class DefaultMqttCallBack extends AbsMqttCallBack {

    @Autowired
    private MqttMessageService messageService;
    @Value("${spring.profiles.active}")
    private String activeProfile;

    /**
     * @param topic   主题
     * @param message 消息内容
     */
    @Override
    protected void handleReceiveMessage(String topic, String message) {
        log.info("mqttReceiveMessage 主题={} 消息={}", topic, message);
        // 此处应该单独为系统注册一个客户端去接收设备客户端的消息？但是会有问题，此处单独注册的客户端接收到消息能否代表其他设备客户端也收到消息？
        // 消息入库
        saveMqttMessage(topic, message);
    }

    private void saveMqttMessage(String topic, String message) {
        // 自定义消息处理业务
        MqttMessage msg = new MqttMessage();
        msg.setMqttTopic(topic);
        msg.setMessageContent(message);
        msg.setEnv(activeProfile);
        msg.setCreateTime(new Date());
        messageService.addOne(msg);
    }
}